from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
from database import Session, engine
import datetime
from dao import DaoResolventList
import logging
from model.ModResolventList import ResolventList as rl

class ResolventList(HTTPEndpoint):

    def __init__(self, scope):
        super().__init__(scope)
        self._logger = logging.getLogger(type(self).__name__)

    async def get(self, request):
        session = Session()
        try:
           proid = request.query_params["proid"]
           return  DaoResolventList.get_resolvent_info(session, proid)
        finally:
            session.close()

    async def post(self, request):
        session = Session()
        try:
            dict_res = await request.json()
            res = rl()
            message_str = ""
            if len(dict_res["resolname"]) > 0:
                res.resolname = dict_res.get("resolname")
            else:
                message_str = "解决方法"
            res.proid = dict_res.get("proid")
            res.replace_equipment_flag = dict_res.get("replace_equipment_flag")
            res.classifyid = dict_res.get("classifyid")
            a = DaoResolventList.get_res_max(session, dict_res["proid"])
            b = int(a)+1
            res.resolid = str(b).zfill(2)
            if len(message_str) > 0:
                last_str = message_str[-1]
                if last_str == "、":
                    message_str = message_str[:-1]
                message_str = "请确认：" + message_str + "等信息是否填写完整！"
                return JSONResponse({"result": "2", "message_str": message_str})
            DaoResolventList.insert_res(session, res)
            session.commit()
            return JSONResponse({"result": "1"})
        except Exception as e:
            self._logger.info(e)
            session.rollback()
            return JSONResponse({"result": "0"})
        finally:
            session.close()